package pl.ncdc.web.login.server.service;

import java.io.File;
import java.io.FilenameFilter;

import pl.ncdc.web.login.client.User;
import pl.ncdc.web.login.client.service.UserService;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * Demo version of {@link UserService}.
 * <p>
 * Created on Apr 17, 2008
 *
 * @author hshsce
 * @version $Id: DemoUserService.java 43 2008-04-19 10:26:10Z hshsce $
 */
public class DemoUserService extends RemoteServiceServlet implements UserService {

	private final File m_userImagesDir = new File("src/demo/pl/ncdc/web/login/public/images/users");

	public User[] list() {
		final File[] images = m_userImagesDir.listFiles(new FilenameFilter() {
			public boolean accept(final File dir, final String name) {
				return (name.endsWith(".jpg"));
			}
		});
		final User[] users = new User[images.length];
		for (int i = 0; i < users.length; i++) {
			final String fileName = images[i].getName();
			final String uid = fileName.substring(0, fileName.lastIndexOf(".jpg"));
			final User user = new User();
			user.setUid(uid);
			user.setFullName(uid.toUpperCase() + ' ' + uid);
			users[i] = user;
		}
		return users;
	}

	public String[] suggestUid(final String query) {
		final File[] images = m_userImagesDir.listFiles(new FilenameFilter() {
			public boolean accept(final File dir, final String name) {
				return (name.endsWith(".jpg") && (name.substring(0, name.lastIndexOf(".jpg")).startsWith(query)));
			}
		});
		final String[] users = new String[images.length];
		for (int i = 0; i < users.length; i++) {
			final String fileName = images[i].getName(); 
			users[i] = fileName.substring(0, fileName.lastIndexOf(".jpg"));
		}
		return users;
	}

}
